#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>

#define HEARTBEATS_PORT 36663

static int count = 0;
static struct itimerval oldtv;

struct seg_arguments{
unsigned int minval;	//min number of segments
unsigned int maxval;	//max number of segments
unsigned int thbeat;	//heartbeat time
}arg;

struct sockaddr_in si_other;
struct in_addr localInterface;
struct sockaddr_in groupSock;

pid_t srv_listen = -1;
int maxtime = 0;

char gates_adr[][28] = {	//to be replaced with real lab nodes addresses
	"tile-0-0.local", 
	"tile-0-1.local", 
	"tile-0-2.local", 
	"tile-0-3.local",
	"tile-1-0.local", 
	"tile-1-1.local", 
	"tile-1-2.local",
	"tile-1-3.local", 
	"tile-2-0.local", 
	"tile-2-1.local", 
	"tile-2-2.local",
	"tile-2-3.local", 
	"tile-3-0.local", 
	"tile-3-1.local",
	"tile-3-2.local",
	"tile-3-3.local", 
	"tile-4-0.local", 
	"tile-4-1.local", 
	"tile-4-2.local",
	"tile-4-3.local", 
	"tile-5-0.local", 
	"tile-5-1.local",
	"tile-5-2.local", 
	"tile-5-3.local",
	"tile-6-0.local", 
	"tile-6-1.local", 
	"tile-6-2.local", 
	"tile-6-3.local"	};

void set_timer(){
	struct itimerval itv;
	itv.it_interval.tv_sec = 1;
	itv.it_interval.tv_usec = 0;
	itv.it_value.tv_sec = 1;
	itv.it_value.tv_usec = 0;
	setitimer(ITIMER_REAL, &itv, &oldtv);
}

void signal_handler(int m){
	printf("Waiting for %i seconds\n", count+1);

	if (count >= maxtime) kill(srv_listen, SIGKILL); 
	else count++;
}

void diep(char *s){
	perror(s);
	exit(1);
}

int kill_the_last(char *kill_addr, char *kill_port){
	//sending kill_all signal to everyone else by broadcast to port 366666
	//here we have a client
	char buf[3];

  	int  s, i, slen=sizeof(si_other);
  	int ilen = 0;
	int len;

  	if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
    	diep("socket");
	
	//REUSE THINGS	
	int reuse = 1;
	if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse)) < 0)
	{
		perror("Setting SO_REUSEADDR error");
		close(s);
		exit(1);
	}
	else
	{
		printf("Setting SO_REUSEADDR...OK.\n");
	}
	//////////////////


	memset((char *) &groupSock, 0, sizeof(groupSock));
	groupSock.sin_family = AF_INET;
	groupSock.sin_addr.s_addr = inet_addr(kill_addr);
	groupSock.sin_port = htons(atoi(kill_port));
	
	localInterface.s_addr = inet_addr("127.0.0.1");
	if(setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, (char *)&localInterface, sizeof(localInterface)) < 0)
	{
		perror("Setting local interface error\n");
		exit(1);
	}	
	else
	{
		printf("Setting the local interface...OK\n");
	}

	sprintf(buf, "SLF");
        len = sizeof( struct sockaddr);
        if (sendto(s, buf, 3, 0, (struct sockaddr*)&groupSock, sizeof(groupSock) )==-1)
        //diep("sendto()");	for now it can't make the connection anyway because of wrong port logic so only error msg
	printf("Couldn't send the kill message to %s:%s\n", kill_addr, kill_port);	

return 0;
}


int spread_the_worm(int gate_num){
	
printf("Sending file to gate nr %i: %s, port 36000\n", gate_num, gates_adr[gate_num]);
	////////////////////////////////////////	
	//sending file socket client connection	needed here
	////////////////////////////////////////

return 0;
}



int main(int argc, char *argv[]){

	unsigned int seg_counter = 0;
	unsigned int gate_num;


	int i; 
	int segment_already_stored = 0;

	struct sockaddr_in si_me, si_other;
	int s, slen=sizeof(si_other);
	char buf[64];
	char cport[5];


///////////this block - 'if' conditions - exists only for testing purposes - can be deleted when merged with suicide_main.c

	if ( argc != 4 ){
		printf("Worm arguments not specified. \nUse: %s minvalue maxvalue theartbeat\n", argv[0]);
		exit(0);
	}

	arg.minval = atoi(argv[1]);
	arg.maxval = atoi(argv[2]);
	arg.thbeat = atoi(argv[3]);

	if (arg.minval > arg.maxval){
		printf("Specified minvalue bigger than maxvalue.\nUse: %s minvalue maxvalue theartbeat\n", argv[0]);
		exit(0);
	}

//////////////////////////////////////////////////

	


	srand (time(NULL));
	char *segments_adr[10*arg.maxval][28]; 
	char *segments_port[10*arg.maxval][5]; 
	maxtime = arg.maxval*10;


	while(1){	//infinite listening + killing/creating

		for(i=0; i<10*arg.maxval; i++){		
			segments_adr[i][0] = "\0";
			segments_port[i][0] = "\0";
		}


	
		seg_counter = 0;
		count = 0;

		signal(SIGALRM, signal_handler);
		set_timer();
	
		while(count < 10*arg.thbeat) {
			
		
			
			////////////////////////////////////////
			//waiting for incoming heartbeats (server connection)
			////////////////////////////////////////
			
			while(1){
				srv_listen = fork();

				if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)	diep("socket");
				

				//REUSE THINGS	
				int reuse = 1;
				if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse)) < 0)
				{
					perror("Setting SO_REUSEADDR error");
					close(s);
					exit(1);
				}
				else
				{
					printf("Setting SO_REUSEADDR...OK. - server\n");
						
				}
				//////////////////



	
				memset((char *) &si_me, 0, sizeof(si_me));
				si_me.sin_family = AF_INET;
				si_me.sin_port = htons(HEARTBEATS_PORT);
				si_me.sin_addr.s_addr = htonl(INADDR_ANY);
				if (bind(s, (struct sockaddr *)&si_me, sizeof(si_me))==-1) diep("bind");
  
				

				if (srv_listen == 0) {

				if (recvfrom(s, buf, 64, 0, (struct sockaddr *)&si_other, &slen)==-1) diep("recvfrom()");
				printf("Received packet from %s:%d\nData: %s\n\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port),buf);

    				sprintf(cport, "%d", ntohs(si_other.sin_port));

				for(i=0; i<seg_counter; i++) {
					if (strcmp(inet_ntoa(si_other.sin_addr), segments_adr[i][0])==0){
						if(strcmp(cport, segments_port[i][0])==0){
							segment_already_stored = 1; break;
						}		
					} 	
				}

				if(segment_already_stored == 0) {
					segments_adr[seg_counter][0] = inet_ntoa(si_other.sin_addr);
					segments_port[seg_counter][0] = cport;
					seg_counter++;
				}
					
				close(s);

				}////////
				
			}

		
		}


		printf("Starting the kill/create block:\n");

		if (seg_counter < arg.minval) {
			//creating new segments block
			
			for(seg_counter; seg_counter < arg.minval; seg_counter++){
				gate_num = rand() %28;
				spread_the_worm(gate_num);
			}
			
		}
		
		printf("Updating seg_counter, address and port for test purposes\n");
		seg_counter = 10; 
		//segments_adr[seg_counter][0]="127.0.0.1"; segments_port[seg_counter][0]="12345"; //something is wrong here...

		if (seg_counter > arg.maxval){
			//killing too many segments block

			while(seg_counter > arg.maxval){
				printf("Killing segment nr %i:\n", seg_counter);
				kill_the_last(segments_adr[seg_counter][0], segments_port[seg_counter][0]);
				seg_counter--;
				
			}
		}



	}

	
	return 0;
}